package com.hust.chatvedio;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.gson.Gson;
import com.hust.chatvedio.utils.Utils;

import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {
    private ProgressDialog progressDialog;
    private String message;
    private int success;
    public static String userName;
    public static String userAvatar;
    public static String BaseURL = Utils.BaseURL;
    public static String url_register = BaseURL + "register";
    public static String url_login = BaseURL + "login";
    private TextView mTvHeader;
    private AppCompatEditText mEdUsername;
    private AppCompatEditText mEdPwd;
    private MaterialButton mBtnMain;
    private ImageButton mBtnClose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusColor(this, false, true, R.color.white);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mTvHeader = (TextView) findViewById(R.id.tv_header);
        mEdUsername = (AppCompatEditText) findViewById(R.id.ed_username);
        mEdUsername.addTextChangedListener(this);
        mEdPwd = (AppCompatEditText) findViewById(R.id.ed_pwd);
        mEdPwd.addTextChangedListener(this);
        mBtnMain = (MaterialButton) findViewById(R.id.btn_main);
        mBtnClose = (ImageButton) findViewById(R.id.btn_close);
        mBtnClose.setOnClickListener(this);
        mBtnMain.setOnClickListener(this);
        mBtnMain.setText(LoginActivity.ACTION);
        mBtnMain.setClickable(false);
        mTvHeader.setText("用户" + LoginActivity.ACTION);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main:
                if (mBtnMain.getText().toString().equals("登录")) {
                    login();
                } else {
                    register();
                }
                break;
            case R.id.btn_close:
                finish();
                break;
        }
    }

    private void login() {
        if (mEdUsername.getText().toString().trim().equals("") || mEdPwd.getText().toString().trim().equals("")) {
            Toast.makeText(this, "请输入账号或密码", Toast.LENGTH_LONG).show();
        } else {
            userName = mEdUsername.getText().toString();
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            Map<String, String> map = new HashMap<>();
            map.put("userName", mEdUsername.getText().toString());
            map.put("userPwd", mEdPwd.getText().toString());
            //在进行异步任务前先显示一个 Progress Dialog
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("正在登录...");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.show();

            String s = new Gson().toJson(map);
            Request request = new JsonObjectRequest(1, url_login,
                    s, jsonObject -> {
                try {
                    success = jsonObject.getInt("success");
                    message = jsonObject.optString("message");
                    userAvatar = jsonObject.optString("avatar");
                    if (success == 1) {
                        progressDialog.dismiss();
                        Intent intent = new Intent(MainActivity.this,
                                MenuActivity.class);
                        startActivity(intent);
                    } else if (success == 0) {
                        progressDialog.dismiss();
                        showDialog(MainActivity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, volleyError -> Log.d("error", "onErrorResponse: " + volleyError.toString()));
            requestQueue.add(request);
        }
    }

    private void register() {
        if
        (mEdUsername.getText().toString().trim().equals("") || mEdPwd.getText().toString().trim().equals("")) {
            Toast.makeText(this, "请输入账号或密码", Toast.LENGTH_LONG).show();
        } else {
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            Map<String, String> map = new HashMap<>();
            map.put("userName", mEdUsername.getText().toString());
            map.put("userPwd", mEdPwd.getText().toString());
            //在进行异步任务前先显示一个 Progress Dialog
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("正在注册...");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.show();
            //定义请求
            Request request = new JsonObjectRequest(1, url_register,
                    new Gson().toJson(map), jsonObject -> {
                try {

                    success = jsonObject.getInt("success");
                    message = jsonObject.optString("message");

                    progressDialog.dismiss();
                    showDialog(MainActivity.this, message);
                    mEdUsername.setText("");
                    mEdPwd.setText("");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, volleyError -> Log.d("error", "onErrorResponse: " + volleyError.toString()));
            //将请求放入队列
            requestQueue.add(request);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (mEdUsername.getText().toString().trim().equals("") || mEdPwd.getText().toString().trim().equals("")) {
            mBtnMain.setClickable(false);
            mBtnMain.setBackgroundColor(getResources().getColor(R.color.gray_200));
            mBtnMain.setTextColor(getResources().getColor(R.color.gray_700));
        } else {
            mBtnMain.setClickable(true);
            mBtnMain.setBackgroundColor(getResources().getColor(R.color.green_700));
            mBtnMain.setTextColor(getResources().getColor(R.color.white));
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    private void showDialog(Context context, String message) {
        MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(context);
        materialAlertDialogBuilder
                .setMessage(message)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        finish();
                    }
                });
        materialAlertDialogBuilder.show();
    }
}